import { createRouter, createWebHistory } from 'vue-router'
import axios from 'axios'
import service from '../utils/request'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/modules/user'
import { useAdminStore } from '@/stores/modules/admin'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../components/Register.vue'),
    props: false
  },
  {
    path: '/goods/detail',
    name: 'GoodsDetail',
    component: () => import('../views/GoodsDetail.vue')
  },
  {
    path: '/shop',
    name: 'ShopList',
    component: () => import('../views/ShopDetail.vue')
  },
  {
    path: '/shop/:id',
    name: 'ShopDetail',
    component: () => import('../views/ShopDetail.vue'),
    props: true
  },
  {
    path: '/cart',
    name: 'Cart',
    component: () => import('../views/Cart.vue')
  },
  {
    path: '/checkout',
    name: 'Checkout',
    component: () => import('../views/Checkout.vue')
  },
  {
    path: '/user',
    name: 'UserCenter',
    component: () => import('../views/UserCenter.vue'),
    redirect: '/user/home',
    children: [
      {
        path: 'home',
        name: 'UserHome',
        component: () => import('../components/user/UserHome.vue')
      },
      {
        path: 'orders',
        name: 'UserOrders',
        component: () => import('../components/user/UserOrders.vue')
      },
      {
        path: 'favorites',
        name: 'UserFavorites',
        component: () => import('../components/user/UserFavorites.vue')
      },
      {
        path: 'comments',
        name: 'UserComments',
        component: () => import('../components/user/UserComments.vue'),
        meta: { requiresAuth: true, title: '我的评论' }
      },
      {
        path: 'coupons',
        name: 'UserCoupons',
        component: () => import('../components/user/UserCoupons.vue')
      },
      {
        path: 'address',
        name: 'UserAddress',
        component: () => import('../components/user/UserAddress.vue')
      },
      {
        path: 'settings',
        name: 'UserSettings',
        component: () => import('../components/user/UserSettings.vue')
      },
      {
        path: 'apply-shop',
        name: 'ApplyShop',
        component: () => import('../views/user/ApplyShop.vue'),
        meta: { requiresAuth: true, title: '商家入驻申请' }
      },
      {
        path: 'after_sale',
        name: 'UserAfterSale',
        component: () => import('../components/user/UserAfterSale.vue'),
        meta: { requiresAuth: true, title: '我的售后' }
      },
      {
        path: 'after_sale/:id',
        name: 'UserAfterSaleDetail',
        component: () => import('../components/user/UserAfterSaleDetail.vue'),
        meta: { requiresAuth: true, title: '售后详情' }
      },
      {
        path: 'service',
        name: 'UserService',
        component: () => import('../components/user/UserService.vue'),
        meta: { requiresAuth: true, title: '客户服务' }
      },
    ]
  },
  {
    path: '/payment',
    name: 'Payment',
    component: () => import('@/views/Payment.vue')
  },
  {
    path: '/search',
    name: 'Search',
    component: () => import('../views/Search.vue')
  },
  {
    path: '/orders/:id',
    name: 'OrderDetail',
    component: () => import('../views/OrderDetail.vue')
  },
  {
    path: '/logistics/:orderId',
    name: 'LogisticsTracking',
    component: () => import('../views/LogisticsTracking.vue'),
    meta: { requiresAuth: true, title: '物流追踪' }
  },
  {
    path: '/jiang/adminLogin',
    name: 'AdminLogin',
    component: () => import('../views/admin/Login.vue'),
    meta: { title: '后台登录' }
  },
  {
    path: '/jiang',
    name: 'Jiang',
    component: () => import('../views/admin/AdminLayout.vue'),//后台布局
    redirect: '/jiang/dashboard',
    meta: { 
      requiresAuth: true,
      requiresAdmin: true 
    },
    children: [
      {
        path: 'dashboard',
        name: 'AdminDashboard',
        component: () => import('../views/admin/Dashboard.vue'),//控制台
        meta: { title: '控制台', icon: 'Monitor' }
      },
      {
        path: 'shop',
        name: 'AdminShop',
        component: () => import('../views/admin/shop/ShopList.vue'),//店铺管理
        meta: { title: '店铺管理', icon: 'Shop', group: '店铺' }
      },
      {
        path: 'shop/add',
        name: 'AdminShopAdd',
        component: () => import('../views/admin/shop/ShopForm.vue'),//添加店铺
        meta: { title: '添加店铺', showInMenu: false }
      },
      {
        path: 'shop/edit/:id',
        name: 'AdminShopEdit',
        component: () => import('../views/admin/shop/ShopForm.vue'),//编辑店铺
        meta: { title: '编辑店铺', showInMenu: false }
      },
      {
        path: 'goods',
        name: 'AdminGoods',
        component: () => import('../views/admin/goods/GoodsList.vue'),//商品管理
        meta: { title: '商品管理', icon: 'Goods', group: '商品' }
      },
      {
        path: 'goods/add',
        name: 'AdminGoodsAdd',
        component: () => import('../views/admin/goods/GoodsForm.vue'),//添加商品
        meta: { title: '添加商品', group: '商品', showInMenu: false }
      },
      {
        path: 'goods/edit/:id',
        name: 'AdminGoodsEdit',
        component: () => import('../views/admin/goods/GoodsForm.vue'),//编辑商品
        meta: { title: '编辑商品', showInMenu: false }
      },
      {
        path: 'orders',
        name: 'AdminOrders',
        component: () => import('../views/admin/orders/OrderList.vue'),//订单管理
        meta: { title: '订单管理', icon: 'List', group: '订单' }
      },
      {
        path: 'orders/:id',
        name: 'AdminOrderDetail',
        component: () => import('../views/admin/orders/OrderDetail.vue'),//订单详情
        meta: { title: '订单详情', showInMenu: false }
      },
      {
        path: 'cart',
        name: 'AdminCart',
        component: () => import('../views/admin/cart/CartList.vue'),//购物车管理
        meta: { title: '购物车管理', icon: 'ShoppingCart', group: '购物车' }
      },
      {
        path: 'service',
        name: 'AdminService',
        component: () => import('../views/admin/service/Service.vue'),//客户服务
        meta: { title: '客户服务', icon: 'Service', group: '客户服务' }
      },
      {
        path: 'users',
        name: 'AdminUsers',
        component: () => import('../views/admin/users/UserList.vue'),//用户管理
        meta: { title: '用户管理', icon: 'User', group: '用户'}
      },
      {
        path: 'users/edit/:id',
        name: 'AdminUserEdit',
        component: () => import('../views/admin/users/UserForm.vue'),
        meta: { title: '编辑用户', showInMenu: false }
      },
      {
        path: 'users/add',
        name: 'AdminUserAdd',
        component: () => import('../views/admin/users/UserForm.vue'),
        meta: { title: '新增用户', showInMenu: false }
      },
      {
        path: 'categories',
        name: 'AdminCategories',
        component: () => import('../views/admin/categories/CategoryList.vue'),//分类管理
        meta: { title: '分类管理', icon: 'Grid', group: '商品' }
      },
      {
        path: 'settings',
        name: 'AdminSettings',
        component: () => import('../views/admin/settings/Settings.vue'),//系统设置
        meta: { title: '系统设置', icon: 'Setting', group: '系统管理' }
      },
      {
        path: 'admins',
        name: 'AdminAccountList',
        component: () => import('../views/admin/AdminAccountList.vue'),
        meta: { title: '后台管理员账号管理', requiresAdmin: true, group: '系统管理' }
      },
      {
        path: 'roles',
        name: 'AdminRoles',
        component: () => import('../views/admin/role/RoleList.vue'),
        meta: { 
          title: '角色管理', 
          icon: 'UserFilled',
          group: '系统管理',
          requiresAdmin: true 
        }
      },
      {
        path: 'permissions',
        name: 'AdminPermissions',
        component: () => import('../views/admin/permission/PermissionList.vue'),
        meta: { 
          title: '权限管理', 
          icon: 'Lock',
          group: '系统管理',
          requiresAdmin: true 
        }
      }
    ]
  },
  {// 商家页面
    path: '/merchant', // 商家路由前缀
    name: 'MerchantLayout', 
    component: () => import('../views/merchant/MerchantLayout.vue'), // 更改为布局组件
    meta: { requiresAuth: true, requiresMerchant: true }, // 需要登录且是商家权限
    children: [
      // 仪表盘
      {
        path: '', // 默认路由
        name: 'MerchantHome',
        component: () => import('../views/merchant/MerchantDashboard.vue'),
        meta: { requiresAuth: true, requiresMerchant: true }
      },
      {
        path: 'dashboard',
        name: 'MerchantDashboard',
        component: () => import('../views/merchant/MerchantDashboard.vue'),
        meta: { requiresAuth: true, requiresMerchant: true }
      },
      // 商品管理
      {
        path: 'goods',
        name: 'MerchantGoodsList',
        component: () => import('../views/merchant/GoodsList.vue'),
        meta: { requiresAuth: true, requiresMerchant: true }
      },
      {
        path: 'goods/add',
        name: 'MerchantAddGoods',
        component: () => import('../views/merchant/AddGoods.vue'),
        meta: { requiresAuth: true, requiresMerchant: true }
      },
      {
        path: 'goods/edit/:id', // :id 为商品ID参数
        name: 'MerchantEditGoods',
        component: () => import('../views/merchant/EditGoods.vue'),
        meta: { requiresAuth: true, requiresMerchant: true }
      },
      // 订单管理
      {
        path: 'orders',
        name: 'MerchantOrderList',
        component: () => import('../views/merchant/OrderList.vue'),
        meta: { requiresAuth: true, requiresMerchant: true }
      },
      {
        path: 'orders/:id', // :id 为订单ID参数
        name: 'MerchantOrderDetail',
        component: () => import('../views/merchant/OrderDetail.vue'),
        meta: { requiresAuth: true, requiresMerchant: true }
      },
      // 店铺设置
      {
        path: 'settings',
        name: 'MerchantSettings',
        component: () => import('../views/merchant/StoreSettings.vue'),
        meta: { requiresAuth: true, requiresMerchant: true }
      },
      // 营销管理 (示例：优惠券)
      {
        path: 'coupons',
        name: 'MerchantCouponManagement',
        component: () => import('../views/merchant/CouponManagement.vue'),
        meta: { requiresAuth: true, requiresMerchant: true }
      },
      //售后管理
      {
        path: 'after_sale',
        name: 'MerchantAfterSale',
        component: () => import('../views/merchant/AfterSale.vue'),
        meta: { requiresAuth: true, requiresMerchant: true, title: '售后管理' }
      },
      //售后详情
      {
        path: 'after_sale/:id',
        name: 'MerchantAfterSaleDetail',
        component: () => import('../views/merchant/AfterSaleDetail.vue'),
        meta: { requiresAuth: true, requiresMerchant: true, title: '售后详情' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  // 配置路由的滚动行为
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 需要登录才能访问的路由
const authRoutes = ['/user', '/orders', '/favorites', '/cart', '/checkout', '/admin']

//平台后台需要登录才能访问的路由
const adminAuthRoutes = ['/jiang', '/jiang/dashboard', '/jiang/shop', '/jiang/goods', '/jiang/orders', '/jiang/users', '/jiang/settings', '/jiang/admins', '/jiang/roles', '/jiang/permissions', '/jiang/service']

//商家后台需要登录才能访问的路由
const merchantAuthRoutes = ['/merchant', '/merchant/dashboard', '/merchant/goods', '/merchant/orders', '/merchant/settings', '/merchant/after_sale']


// 清除所有认证相关的cookie
const clearAuthCookies = () => {
  const cookies = ['token', 'phone', 'nickName', 'icon']
  cookies.forEach(name => {
    document.cookie = `${name}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`
  })
}

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 后台管理系统` : '电商平台'
  
  const userStore = useUserStore()
  const adminStore = useAdminStore()
  const isAuthRoute = authRoutes.some(route => to.path.startsWith(route))
  const isAdminRoute = adminAuthRoutes.some(route => to.path.startsWith(route)) && to.path !== '/jiang/adminLogin'
  const isMerchantRoute = merchantAuthRoutes.some(route => to.path.startsWith(route))
  const isLoginPage = to.path === '/login'
  const isAdminLoginPage = to.path === '/jiang/adminLogin'

  // 如果是登录页面且已登录，重定向到首页
  if (isLoginPage && userStore.accessToken) {
    return next('/')
  }

  // 如果是后台登录页面且已登录且有管理员权限，重定向到后台首页
  if (isAdminLoginPage && adminStore.accessToken) {
    return next('/jiang/dashboard')
  }

  // 处理平台后台路由
  if (isAdminRoute) {
    // 检查管理员是否已登录
    if (!adminStore.accessToken || !adminStore.adminInfo) {
      // 未登录，重定向到后台登录页
      return next({
        path: '/jiang/adminLogin',
        query: { redirect: to.fullPath }
      })
    }
    
    // 尝试刷新令牌
    try {
      const refreshed = await adminStore.checkAndRefreshToken()
      if (refreshed) {
        return next()
      } else {
        console.error('刷新管理员令牌失败')
        clearAuthCookies()
        return next({
          path: '/jiang/adminLogin',
          query: { redirect: to.fullPath }
        })
      }
    } catch (error) {
      console.error('刷新管理员令牌失败:', error)
      clearAuthCookies()
      return next({
        path: '/jiang/adminLogin',
        query: { redirect: to.fullPath }
      })
    }
  }

  // 处理商家后台路由
  if (isMerchantRoute) {
    console.log('进入商家路由守卫, 路径:', to.path)
    try {
      // 检查并刷新token
      const isValid = await userStore.checkAndRefreshToken()
      console.log('token有效性:', isValid, '用户信息:', userStore.userInfo)
      console.log('是否是商家:', userStore.userInfo?.isMerchant)
      
      // 如果没有用户信息或者不是商家，尝试重新检查商家状态
      if (isValid && userStore.userInfo && !userStore.userInfo.isMerchant) {
        try {
          const { isShop } = await import('@/api/shop')
          const isMerchant = await isShop()
          console.log('重新检查商家身份:', isMerchant)
          if (typeof isMerchant === 'boolean' && isMerchant) {
            userStore.updateUserMerchantStatus(true)
            console.log('更新商家身份成功')
            return next()
          }
        } catch (error) {
          console.error('重新检查商家身份失败:', error)
          // 继续执行下面的检查
        }
      }
      
      if (!isValid || !userStore.userInfo?.isMerchant) {
        // 未登录或非商家，重定向到登录页
        console.log('重定向到登录页，原因:', !isValid ? 'token无效' : '非商家身份')
        return next({
          path: '/login',
          query: { redirect: to.fullPath }
        })
      }
      console.log('商家身份验证通过，允许访问')
      return next()
    } catch (error) {
      console.error('商家路由守卫错误:', error)
      return next('/login')
    }
  }

  // 如果不需要认证，直接放行
  if (!isAuthRoute && !isAdminRoute && !isMerchantRoute) {
    return next()
  }

  // 普通需要认证的路由
  if (isAuthRoute) {
    // 检查用户是否已登录
    if (!userStore.accessToken || !userStore.userInfo) {
      // 未登录，重定向到登录页
      return next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
    // 尝试刷新令牌
    try {
      await userStore.checkAndRefreshToken()
    } catch (error) {
      console.error('刷新用户令牌失败:', error)
    }
    return next()
  }

  // 检查管理员权限
  if (to.meta.requiresAdmin && !adminStore.accessToken) {
    ElMessage.error('需要管理员权限')
    return next('/')
  }

  // 检查商家权限
  if (to.meta.requiresMerchant && !userStore.userInfo?.isMerchant) {
    ElMessage.error('需要商家权限')
    return next('/')
  }

  // 验证通过，放行
  return next()
})

// 全局后置钩子
router.afterEach((to, from) => {
  console.log(`从 ${from.path} 路由切换到 ${to.path}`)
})

// 添加返回按钮事件监听
window.addEventListener('popstate', (event) => {
  if (event.state) {
    event.state.back = true
  }
})

// 路由错误处理
router.onError((error) => {
  console.error('路由错误：', error)
  // 可以在这里统一处理路由错误
})

export default router